package com.cafuc.javaEE.filter;

import jdk.internal.dynalink.beans.StaticClass;
import org.apache.tomcat.util.http.ResponseUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

// @WebFilter(filterName = "authFilter", urlPatterns = {"/*"})
public class AuthFilter implements Filter {
    public static List<String> ALLOW_LISt = new ArrayList<String>(){{
        add("/login");
        add("/login");
        add("/register");
        add("/static");
        add("/logout");
    }};
    // /login
    public  boolean checkUri(String uri) {
        String result = ALLOW_LISt.stream()
                .filter(item -> item.equals(uri) ||uri.startsWith(item))
                .findFirst()
                .orElse(null);
        return result != null;
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //获取请求的 uri
        String uri = req.getRequestURI();
        //如果 uri 满足放行列表规则 或者 登录 放行，否则 重定向到登录页面
        if(checkUri(uri) || req.getSession().getAttribute("user") != null){
            filterChain.doFilter(req, resp);
        } else {
            resp.sendRedirect("/login");
        }
    }
}
